#pragma once

#include "Log.hpp"

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include<unordered_map>

class Util
{
public:
    static std::string GetSuffix(const std::string &suffix)
    {
        // 建表
        unordered_map<string, string> hash =
            {
                {".txt", "text/plain"},
                {".htm", "text/html"},
                {".html", "text/html"},
                {".jpg", "image/jpeg"},
                {".jpeg", "image/jpeg"},
                {".png", "image/png"},
                {".mp3", "audio/mp3"},
                {".avi", "video/avi"},
                {".mp4", "video/mpeg4"}};

        if (hash.count(suffix) == 0)
            return "text/html";

        return hash[suffix];
    }

    static bool ReadFile(const std::string &path, std::string *outStr)
    {
        // 获取文件信息
        struct stat st;
        if (stat(path.c_str(), &st) < 0)
            return false;

        // 扩出足够大的空间
        int n = st.st_size;
        outStr->resize(n + 1);

        // 打开文件
        int fd = open(path.c_str(), O_RDONLY);
        if (fd < 0)
            return false;

        // 读取文件
        int size = read(fd, (char *)outStr->c_str(), n);

        close(fd);

        logMessage(Info, "Read file %s done", outStr->c_str());

        // 实际读取到的大小，应该与文件的大小一致
        return size == n;
    }

    static int ReadLine(const std::string &url, int i, const std::string &SEP, std::string *line)
    {
        int pos = url.find(SEP, i);
        *line = url.substr(i, pos - i);
        return pos;
    }
};
